<template>
  <div class="files">
    <div class="files__tool" v-show="selectedFilesId.length > 0">
      <yk-space>
        <yk-checkbox :checked="checkedAll" :indeterminate="indeterminate" @change="handleChangeAll">
          全选
        </yk-checkbox>
        <yk-text>已选择 {{ selectedFilesId.length }} 项内容</yk-text>
        <yk-text type="primary" style="cursor: pointer" @click="removeAll">取消选择</yk-text>
      </yk-space>
      <yk-space>
        <IconDeleteOutline class="files__tool-delete" @click="deleteFiles"></IconDeleteOutline>
        <yk-popconfirm title="选择分组" trigger="hover" placement="bottomRight" @cancel="cancel" @confirm="confirm">
          <IconSwitchOutline class="files__tool-switch"></IconSwitchOutline>
          <template #content>
            <yk-scrollbar ref="scrollbar" height="148px" class="subset">
              <div @click="changeOption(item.id)" v-for="item in subsetStore.data" :key="item.id" class="subset__item"
                :class="{ 'subset-selected': subsetSelectedId === item.id }">
                {{ item.name }} {{ item.value }}
              </div>
            </yk-scrollbar>
          </template>
        </yk-popconfirm>

      </yk-space>
    </div>
    <div class="files__main">
      <filesItem v-for="item in files" :key="item.id" :data="item" @changeSubsetId="changeSubset" @delete="deleteFIle"
        @selected="selectFile">
      </filesItem>
    </div>
    <div class="pagination" v-show="count / props.pageSize > 1">
      <yk-pagination size="m" :total="count" @change="changePage" :default-page-size="props.pageSize" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import filesItem from './filesItem.vue'
import { useSubsetStore } from '@/stores/subset';
import { fileAPI, deleteFileAPI, removeFileAPI } from '@/api';

import { useCode } from '@/hooks/code';
import { useUserStore } from '@/stores/user';

const proxy: any = getCurrentInstance()?.proxy
const userStore = useUserStore()
const { tackleCode } = useCode()

import './file.less'
const subsetStore = useSubsetStore();
type FileProps = {
  pageSize: number
  subsetId: number | string
}
const props = withDefaults(defineProps<FileProps>(), {
  pageSize: 16,
  subsetId: -1,
})

// 总数
const count = ref<number>(123)

// 数据内容
const files = ref()

// 请求
type Request = {
  token?: string
  pageSize: number
  nowPage: number,
  subsetId?: number | string
  count?: boolean
}

const request: Request = {
  token: userStore.token, // 用户token
  pageSize: props.pageSize,
  subsetId: props.subsetId,
  nowPage: 1,
  count: false, // 是否获取总数
}

// 获取数据
const drwData = async (e: boolean) => {

  request.count = e
  const res: any = await fileAPI(request);
  if (tackleCode(res.code)) {
    console.log(res);
    if (e) {
      count.value = res.data.count;
    }
    const arr = res.data.list
    // 加入选择项
    arr.forEach((item: any) => {
      item.selected = false
    })
    files.value = arr
    console.log('files', files.value)
  }

}


// files.value = data.list.slice(
//   (request.nowPage - 1) * request.pageSize,
//   request.nowPage * request.pageSize,
// )


const indeterminate = ref(false)
const checkedAll = ref(false)
const handleChangeAll = (value: boolean) => {
  indeterminate.value = false
  // 先清空选择ID
  selectedFilesId.value = []
  if (value) {
    checkedAll.value = true
    files.value.forEach((item: any) => {
      item.selected = true
      selectedFilesId.value.push(item.id)
    })
  } else {
    checkedAll.value = false
    files.value.forEach((item: any) => {
      item.selected = false
    })
  }
}

// 取消选择
const removeAll = () => {
  indeterminate.value = false
  checkedAll.value = false
  files.value.forEach((item: any) => {
    item.selected = false
  })
  selectedFilesId.value = []
}

// 被选中图片ID的数组
const selectedFilesId = ref<number[]>([])

// 选择操作
const selectFile = (e: number) => {
  for (let i = 0; i < files.value.length; i++) {
    if (files.value[i].id === e) {
      files.value[i].selected = !files.value[i].selected
      if (files.value[i].selected) {
        selectedFilesId.value.push(e)
      } else {
        // 从数组移除对应项
        selectedFilesId.value = selectedFilesId.value.filter(item => item !== e)
      }
      // 半选与全选
      if (selectedFilesId.value.length === 0) {
        indeterminate.value = false
        checkedAll.value = false
      } else if (selectedFilesId.value.length === files.value.length) {
        indeterminate.value = false
        checkedAll.value = true
      } else {
        indeterminate.value = true
        checkedAll.value = false
      }
    }
  }
}

// 删除单张图片
const deleteFIle = async (id: number, url: string) => {

  const request = {
    token: userStore.token,
    filesId: id,
    filesUrl: url
  }

  const res: any = await deleteFileAPI(request);
  if (tackleCode(res.code)) {
    files.value = files.value.filter((item: any) => item.id !== id)
    proxy.$message({ type: 'primary', message: '删除成功' })
  }
  else {
    proxy.$message({ type: 'error', message: res.msg || '删除失败' })
  }


}

// 删除选择的图片
const deleteFiles = async () => {


  if (selectedFilesId.value.length > 0) {

    const url = []
    for (let i = 0; i < selectedFilesId.value.length; i++) {
      const item = files.value.find((item: any) => item.id === selectedFilesId.value[i])
      if (item) {
        url.push(item.url)
      }
    }

    const request = {
      token: userStore.token,
      filesId: selectedFilesId.value.join(','),
      filesUrl: url
    }
    const res: any = await deleteFileAPI(request);
    if (tackleCode(res.code)) {
      for (let i = 0; i < selectedFilesId.value.length; i++) {
        files.value = files.value.filter((item: any) => item.id !== selectedFilesId.value[i])
      }
      // 清空选
      selectedFilesId.value = []

      proxy.$message({ type: 'primary', message: '删除成功' })
    }
    else {
      proxy.$message({ type: 'error', message: res.msg || '删除失败' })
    }
  }
}



// 分页查询
const changePage = (e: number) => {
  request.nowPage = e
  drwData(false)
}

// 分类选择
const subsetSelectedId = ref<number | string>()

// 切换分组
const changeOption = (e: number | string) => {
  subsetSelectedId.value = e
}

function cancel() {
  proxy.$message({ type: 'warning', message: '你点击了取消按钮' })
}
// 切换多张
function confirm() {

  const request = {
    token: userStore.token,
    fileId: selectedFilesId.value.join(','),
    subsetId: subsetSelectedId.value
  }

  const res: any = removeFileAPI(request);
  if (tackleCode(res.code)) {

    for (let i = 0; i < selectedFilesId.value.length; i++) {
      // 静态删除
      files.value = files.value.filter((item: any) => {
        return item.id !== selectedFilesId.value[i]
      })
    }
    // 将分组数字修改
    for (let i = 0; i < subsetStore.data.length; i++) {
      if (subsetStore.data[i].id === subsetSelectedId.value) {
        subsetStore.data[i].value += selectedFilesId.value.length
      }
      if (subsetStore.data[i].id === props.subsetId && props.subsetId !== -1) {
        subsetStore.data[i].value -= selectedFilesId.value.length
      }
    }
    selectedFilesId.value = []


    proxy.$message({ type: 'primary', message: '分组切换成功' })
  }

}

// 切换单张图片分组
const changeSubset = (e: any) => {

  const request = {
    token: userStore.token,
    fileId: e.id,
    subsetId: e.subsetId
  }

  const res: any = removeFileAPI(request);
  if (tackleCode(res.code)) {
    // 静态删除
    files.value = files.value.filter((item: any) => {
      return item.id !== e.id
    })

    // 将分组数字修改
    for (let i = 0; i < subsetStore.data.length; i++) {
      if (subsetStore.data[i].id === e.subsetId) {
        subsetStore.data[i].value += 1
      }
      if (subsetStore.data[i].id === props.subsetId && props.subsetId !== -1) {
        subsetStore.data[i].value -= 1
      }
    }
    // 清空选择

    proxy.$message({ type: 'primary', message: '分组切换成功' })
  }

}


watch(
  props, () => {
    // 查询数据
    request.nowPage = 1; // 重置当前页
    request.subsetId = props.subsetId; // 更新分组ID
    drwData(true);
  }
)


onMounted(() => {
  drwData(true)
})
</script>

<style lang="less" scoped>
// 颜色变量
@primary-color: #3a7bd5;
@primary-light: rgba(58, 123, 213, 0.1);
@accent-color: #56ccf2;
@text-color: #2c3e50;
@text-light: #6c7a89;
@bg-color: #ffffff;
@bg-light: #f8fafd;
@border-color: #e8ecf1;
@shadow-light: 0 4px 12px rgba(0, 0, 0, 0.05);
@shadow-medium: 0 8px 24px rgba(0, 0, 0, 0.08);
@transition-time: 0.3s;
@border-radius: 12px;

// 文件管理容器
.files {
  padding: 24px;
  border-radius: @border-radius;
  background: @bg-light;
  width: 100%;
  box-shadow: @shadow-light;
  transition: all @transition-time;

  // 工具栏
  &__tool {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-radius: @border-radius;
    background: @bg-color;
    margin-bottom: 20px;
    box-shadow: @shadow-light;
    transition: all @transition-time;
    border: 1px solid @border-color;

    &:hover {
      box-shadow: @shadow-medium;
    }

    // 操作图标
    &-delete,
    &-switch {
      width: 22px;
      height: 22px;
      color: @text-light;
      cursor: pointer;
      padding: 4px;
      border-radius: 50%;
      transition: all @transition-time;

      &:hover {
        color: @primary-color;
        background-color: @primary-light;
        transform: scale(1.1);
      }
    }

    // 删除按钮特殊效果
    &-delete:hover {
      color: #e74c3c;
      background-color: rgba(231, 76, 60, 0.1);
    }
  }

  // 文件网格
  &__main {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 20px;
    padding: 4px 0 30px;
    transition: all 0.5s ease;

    // 为每个文件卡片添加动画效果
    &>* {
      animation: fadeIn 0.5s ease forwards;
      opacity: 0;
    }

    // 使用LESS兼容的循环方式生成动画延迟
    .generate-delays(19);
  }

  // 递归混合(mixin)来创建延迟
  .generate-delays(@n, @i: 1) when (@i =< @n) {
    &>*:nth-child(@{i}) {
      animation-delay: (@i * 50ms);
    }

    .generate-delays(@n, (@i + 1));
  }

  // 分页区域
  .pagination {
    padding: 16px 0 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    border-top: 1px solid @border-color;

    :deep(.yk-pagination) {
      .yk-pagination-item.is-active {
        background-color: @primary-color;
        border-color: @primary-color;
        box-shadow: 0 2px 6px rgba(58, 123, 213, 0.2);
      }

      .yk-pagination-item:not(.is-active):hover,
      .yk-pagination-prev:hover,
      .yk-pagination-next:hover {
        color: @primary-color;
        border-color: @primary-color;
      }
    }
  }
}

// 分组选择下拉菜单
.subset {
  width: 180px;

  &__item {
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 6px;
    transition: all @transition-time;
    margin-bottom: 4px;
    font-size: 14px;

    &:hover {
      background-color: @primary-light;
      color: @primary-color;
    }
  }

  &-selected {
    background: linear-gradient(135deg, @primary-color, @accent-color);
    color: white;
    font-weight: 500;

    &:hover {
      background: linear-gradient(135deg, @primary-color, @accent-color) !important;
      color: white !important;
    }
  }
}

// 复选框样式优化
:deep(.yk-checkbox) {
  .yk-checkbox__input.is-checked .yk-checkbox__inner {
    background-color: @primary-color;
    border-color: @primary-color;
  }

  &:hover .yk-checkbox__inner {
    border-color: @primary-color;
  }
}

// 文字链接样式
:deep(.yk-text[type="primary"]) {
  color: @primary-color;

  &:hover {
    color: darken(@primary-color, 10%);
    text-decoration: underline;
  }
}

// 添加淡入动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式布局调整
@media (max-width: 1200px) {
  .files {
    &__main {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 16px;
    }
  }
}

@media (max-width: 992px) {
  .files {
    padding: 20px;

    &__tool {
      padding: 14px 16px;
    }

    &__main {
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 14px;
    }
  }
}

@media (max-width: 768px) {
  .files {
    padding: 16px;

    &__tool {
      padding: 12px 14px;
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;

      .yk-space {
        width: 100%;
        flex-wrap: wrap;
        justify-content: space-between;
      }
    }

    &__main {
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 12px;
      padding-bottom: 20px;
    }
  }
}

@media (max-width: 576px) {
  .files {
    padding: 12px;
    border-radius: 8px;

    &__tool {
      border-radius: 8px;
      padding: 10px 12px;
    }

    &__main {
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
      padding-bottom: 16px;
    }

    .pagination {
      padding-top: 12px;

      :deep(.yk-pagination) {
        font-size: 13px;

        .yk-pagination-item,
        .yk-pagination-prev,
        .yk-pagination-next {
          min-width: 28px;
          height: 28px;
          line-height: 28px;
          margin: 0 2px;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .files {
    padding: 10px;

    &__main {
      grid-template-columns: 1fr 1fr;
      gap: 8px;
    }

    &__tool {
      .yk-space:last-child {
        width: 100%;
        justify-content: space-around;
      }

      &-delete,
      &-switch {
        width: 36px;
        height: 36px;
        padding: 8px;
      }
    }
  }
}
</style>
